# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper

  # Builds the url for a posting's listing url on prosper.com
  def prosper_listing_url(posting)
    "http://www.prosper.com/lend/listing.aspx?listingID=#{posting.listing_number}"
  end

  # Builds the url for a posting's image on prosper.com
  def prosper_image_url(posting, size='thumb')
    return default_listing_image_path if posting.primary_image_url.blank?
    slug, format = posting.primary_image_url.split('.', 2)
    "http://images.prosper.com/listing/#{posting.listing_number}/#{slug}_#{size}.#{format}"
  end
  
  # The image used if a listing has no image
  def default_listing_image_path
    'http://www.prosper.com/images/icons/listingnoimagefound.gif'
  end
  
  # Makes an image tag showing whether the user owns a home
  def homeowner_image(which)
    which = which ? "yes" : "no"
    owns = which ? "homeowner" : "renter"
    image_tag "http://www.prosper.com/images/icons/homeowner_#{which}_sm.gif", :title => "#{owns}", :alt => owns
  end
  
  # Makes an image tag showing whether a bank account is verified
  def bank_account_image(which)
    which = which ? 'yes' : 'no'
    image_tag "http://www.prosper.com/images/icons/account_verified_#{which}.gif", :title => "Bank account verified", :alt => "Bank account verified"
  end
  
  # Makes an image that is wide based on percentage, using a posting's percent funded
  def funding_bar_for(posting)
    percentage_bar(posting.percent_funded)
  end
  
  # Makes an image that is wide based on percentage
  def percentage_bar(percent)
    image_tag "http://www.prosper.com/images/utilities/funding_bar.gif", :alt => "", :width => pct(percent), :height => 10
  end
  
  # Formats a number as a percentage
  def pct(number, precision = 0)
    if (0..100).include? number
      "%.#{precision}f" % (number * 100)
    else
      nil
    end
  end
  
  # Formats a number as a percentage, or n/a if not a number
  def percentage(number, precision = 0)
    if value = pct(number, precision)
      "#{value}%"
    else
      'n/a'
    end
  end
  
  # Sets and adds DangerLabs to the page title
  def page_title(title_text=nil)
    return @page_title if title_text.nil? && @page_title
    @page_title = if title_text.blank?
      "DangerLabs Grouper"
    else
      "DangerLabs Grouper - #{title_text}"
    end
  end
  
  def partial(template, locals={}, &block)
    inner_content = block_given? ? capture(&block) : nil
    
    result = case locals # lets us use a default style when we just need to pass one object
    when Hash
      locals[:inner_content] = inner_content
      render :partial => template, :locals => locals
    else
      render :partial => template, :object => locals
    end
    
    #if a block is given, we concat automatically because of ERB's limitations
    #otherwise, <%= needs to be used
    concat(result, block.binding) if block_given?
    result
  end
end
